﻿using DotNetExtensions.AspNet.Http.Events;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;

using MyCookie = DotNetExtensions.AspNet.Http.Cookie;

namespace DotNetExtensions.AspNet.Http
{
    public partial class RestfulHttpRequest
    {

        public const string IGNORE_HEADER = "ACCEPT,ACCEPT-CHARSET,ACCEPT-ENCODING,ACCEPT-LANGUAGE,ACCEPT-RANGES,ACCESS-CONTROL-ALLOW-CREDENTIALS,ACCESS-CONTROL-ALLOW-HEADERS,ACCESS-CONTROL-ALLOW-METHODS,ACCESS-CONTROL-ALLOW-ORIGIN,ACCESS-CONTROL-EXPOSE-HEADERS,ACCESS-CONTROL-MAX-AGE,ACCESS-CONTROL-REQUEST-HEADERS,ACCESS-CONTROL-REQUEST-METHOD,AGE,ALLOW,AUTHORIZATION,CACHE-CONTROL,CONNECTION,CONTENT-DISPOSITION,CONTENT-ENCODING,CONTENT-LANGUAGE,CONTENT-LENGTH,CONTENT-LOCATION,CONTENT-RANGE,CONTENT-TYPE,COOKIE,COOKIE2,DATE,DNT,ETAG,EXPECT,EXPIRES,FORWARDED,FROM,HEADERS,HOST,IF-MATCH,IF-MODIFIED-SINCE,IF-NONE-MATCH,IF-RANGE,IF-UNMODIFIED-SINCE,KEEP-ALIVE,LARGE-ALLOCATION,LAST-MODIFIED,LOCATION,ORIGIN,PRAGMA,PROXY-AUTHENTICATE,PROXY-AUTHORIZATION,PUBLIC-KEY-PINS,PUBLIC-KEY-PINS-REPORT-ONLY,RANGE,REFERER,REFERRER-POLICY,RETRY-AFTER,SERVER,SET-COOKIE,SET-COOKIE2,SOURCEMAP,STRICT-TRANSPORT-SECURITY,TE,TK,TRAILER,TRANSFER-ENCODING,UPGRADE-INSECURE-REQUESTS,USER-AGENT,USER-AGENT: FIREFOX,VARY,VIA,WARNING,WWW-AUTHENTICATE,X-CONTENT-TYPE-OPTIONS,X-DNS-PREFETCH-CONTROL,X-FORWARDED-FOR,X-FORWARDED-HOST,X-FORWARDED-PROTO,X-FRAME-OPTIONS,X-XSS-PROTECTION,";

        private readonly TimeSpan DefaultTimeOut = TimeSpan.FromMinutes(3);
        private uint Busy1 = 0;

        private List<MyCookie> GlobalCookies = new List<MyCookie>();

        public event FileTransferProgressDelegate Progress;
        public event FileTransferProgressDelegate Completed;
        public event FileTransferProgressDelegate Before;
        private readonly Dictionary<long, CancellationTokenSource> Cancellation = new Dictionary<long, CancellationTokenSource>();

        private bool busying => (Busy1) == 1;
        public bool Busying { get => busying; }
        public long RequestId { get; set; }
        private readonly Encoding encoding = Encoding.UTF8;
        public HttpClientFactory.HttpClientKind Kind { get => HttpClientFactory.HttpClientKind.Restful; }

        public RestfulHttpRequest()
        {
            RequestId = 0L;
        }
        public RestfulHttpRequest(Encoding encoding)
        {
            this.encoding = encoding;
        }
        private HttpMethod ChangeMethod(Method method)
        {
            HttpMethod httpMethod = HttpMethod.Get;
            switch (method)
            {
                case Method.GET:
                    httpMethod = HttpMethod.Get;
                    break;
                case Method.POST:
                    httpMethod = HttpMethod.Post;
                    break;
                case Method.PUT:
                    httpMethod = HttpMethod.Put;
                    break;
                case Method.DELETE:
                    httpMethod = HttpMethod.Delete;
                    break;
                default:
                    break;
            }

            return httpMethod;
        }

        private HttpResponse Send(string url, HttpContent httpContent, HttpRequest request, HttpMethod httpMethod)
        {
            HttpResponse httpResponse = new HttpResponse();
            try
            {
                if (request.Headers.Any() == false) request.Headers.Add(new Header("Keep-Alive", "timeout=600"));
                if (request.Cookies.Any() == false) request.Cookies.AddRange(GlobalCookies);

                Busy1 = 1;
                if (url.StartsWith("https")) ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

                Uri uri = new Uri(url);
                var handle = new HttpClientHandler()
                {
                    UseCookies = true
                };
                HttpClient httpClient = new HttpClient(handle);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(request.ContentType));
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                foreach (var item in request.Headers)
                {
                    if (string.IsNullOrEmpty(item.Name) || string.IsNullOrEmpty(item.Value)) continue;

                    if (IGNORE_HEADER.IndexOf(item.Name.ToUpper() + ",") > -1) continue;

                    httpContent.Headers.Add(item.Name, item.Value);
                }


                httpClient.Timeout = DefaultTimeOut;

                var httpRequestMessage = new HttpRequestMessage(httpMethod, uri);
                httpRequestMessage.Content = httpContent;
                HttpResponseMessage response = httpClient.SendAsync(httpRequestMessage).Result;

                var content = response.Content.ReadAsByteArrayAsync().Result;
                int code = (int)response.StatusCode;
                if (!response.IsSuccessStatusCode)
                {
                    httpResponse = new HttpResponse(code, content, encoding);
                    return httpResponse;
                }

                Busy1 = 0;
                httpResponse = new HttpResponse(code, content, null, encoding);
            }
            catch (Exception ex)
            {
                httpResponse = new HttpResponse(500, $"[500] URL={url} , {ex.Message}, {ex.StackTrace}", encoding);
            }
            finally
            {
                Busy1 = 0;
            }

            return httpResponse;
        }

        public HttpResponse Send(string url, HttpRequest request, Method method = Method.POST)
        {
            HttpResponse httpResponse = new HttpResponse();
            try
            {
                HttpContent httpContent = null;

                string stringData = request.StringContent;
                string contentType = request.ContentType.ToLower();

                if (contentType == "application/json")
                {
                    httpContent = new StringContent(stringData, encoding, contentType);
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }
                else if (contentType == "application/x-www-form-urlencoded")
                {
                    httpContent = new StringContent(stringData, encoding, contentType);
                    if (!string.IsNullOrEmpty(stringData))
                    {
                        var keyValues = JsonConvert.DeserializeObject<List<KeyValue>>(stringData);
                        httpContent = new FormUrlEncodedContent(keyValues.Select(kv => new KeyValuePair<string, string>(kv.Name, kv.Value)));
                    }
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                }
                else if (contentType == "multipart/form-data")
                {
                    string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
                    var multipartFormData = new MultipartFormDataContent(boundary);
                    if (!string.IsNullOrEmpty(stringData))
                    {
                        var keyValues = JsonConvert.DeserializeObject<List<KeyValue>>(stringData);

                        multipartFormData.Headers.Remove("Content-Type");
                        multipartFormData.Headers.Add("Content-Type", $"multipart/form-data;boundary={boundary}");
                        foreach (KeyValue item in keyValues)
                        {
                            multipartFormData.Add(new StringContent(item.Value), item.Name);
                        }
                    }
                    httpContent = multipartFormData;
                }

                if (request.MultipartForms.Any())
                {
                    MultipartFormDataContent formDataContent = new MultipartFormDataContent();

                    foreach (var item in request.MultipartForms)
                    {
                        HttpContent subContent = null;
                        if (item.Type == MultipartFormDataType.Stream && item.Value != null)
                        {
                            if (item.Value is System.IO.Stream)
                            {
                                subContent = new StreamContent((System.IO.Stream)item.Value);
                            }
                            else if (item.Value is byte[])
                            {
                                byte[] buffer = (byte[])item.Value;
                                subContent = new StreamContent(new System.IO.MemoryStream(buffer));
                            }
                            else if (item.Value is string)
                            {
                                // 可以使用本地文件方式上传
                                string filename = item.Value.ToString();

                                if (!System.IO.File.Exists(filename)) throw new Exception($"未找到指定文件'{filename}'");

                                subContent = new StreamContent(new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                            }

                            if (subContent != null)
                            {
                                subContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                                {
                                    FileName = "file.jpg",
                                    Name = "file"
                                };
                                subContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                            }
                        }
                        else if (item.Type == MultipartFormDataType.Text && item.Value != null)
                        {
                            subContent = new StringContent(item.Value.ToString(), encoding);
                        }

                        if (subContent != null) formDataContent.Add(subContent);

                        httpContent = formDataContent;
                    }
                }

                httpResponse = Send(url, httpContent, request, ChangeMethod(method));

            }
            catch (Exception ex)
            {
                Busy1 = 0;
                httpResponse = new HttpResponse(500, $"[500] URL={url} , {ex.Message}, {ex.StackTrace}", encoding);
            }
            finally
            {

            }

            return httpResponse;
        }

        public void Dispose()
        {
            RequestId = 0L;
            Cancellation.Clear();
        }

    }
}
